/*
 * $Id: MyBeforeOpenIDAuthenticationFilter.java 42 2013-04-17 15:33:59Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 42 $
 * $Date: 2013-04-17 15:33:59 +0000 (Wed, 17 Apr 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.sci.logisticsmap.web.security.filter;

import com.sci.logisticsmap.web.security.support.SecurityConstants;
import com.sci.logisticsmap.web.security.support.SecurityUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * The class {@code MyBeforeOpenIDAuthenticationFilter} represents the custom filter
 * before OpenID authentication.
 *
 * @author gabakyan@gmail.com (Last modified by $Author: gabakyan $)
 * @version $Revision: 42 $
 */
public class MyBeforeOpenIDAuthenticationFilter implements Filter {
    /**
     * The logger.
     */
    private static final Logger logger;

    /**
     * The app url property.
     */
    private @Value("${app.url}") String appUrl;

    /**
     * The static initialization block.
     */
    static {
        logger = LoggerFactory.getLogger(MyBeforeOpenIDAuthenticationFilter.class);
    }

    /**
     * The class <code>MyBeforeOpenIDAuthenticationFilter.FilteredRequest</code> represents the http servlet request wrapper.
     */
    private class FilteredRequest extends HttpServletRequestWrapper {
        /**
         * Initializes a new filtered request.
         *
         * @param request The http servlet request.
         */
        public FilteredRequest(HttpServletRequest request) {
            super(request);
        }

        /*
         * (non-Javadoc)
         *
         * @see javax.servlet.http.HttpServletRequestWrapper#getRequestURL()
         */
        @Override
        public StringBuffer getRequestURL() {
            StringBuffer url = super.getRequestURL();
            String urlString = url.toString();

            String pathAndQueryString = SecurityUtilities.getPathAndQueryString(urlString);
            //logger.debug("FilteredRequest.getRequestURL: url path and query string = {}", pathAndQueryString);
            if (pathAndQueryString.contains(SecurityConstants.OPENID_LOGIN_PROCESSING_URL)
                    || pathAndQueryString.contains(SecurityConstants.ADMIN_OPENID_LOGIN_PROCESSING_URL)) {
                String serverAndPort = SecurityUtilities.getServerAndPort(urlString);
                logger.debug("FilteredRequest.getRequestURL: url server and port = {}", serverAndPort);

                String appUrlServerAndPort = SecurityUtilities.getServerAndPort(appUrl);
                logger.debug("FilteredRequest.getRequestURL: appUrl server and port = {}", appUrlServerAndPort);

                if (!serverAndPort.equals(appUrlServerAndPort)) {
                    String newUrlString = SecurityUtilities.replaceServerAndPort(urlString, appUrlServerAndPort);
                    logger.debug("FilteredRequest.getRequestURL: new url = {}", newUrlString);
                    return new StringBuffer(newUrlString);
                }
            }

            return url;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // No need to init
    }

    /*
     * (non-Javadoc)
     *
     * @see Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(new FilteredRequest((HttpServletRequest) request), response);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy() {
        // No need to destroy
    }
}
